//
//  LIUWriteToFileUnit.m
//  EasyNotes
//
//  Created by 劉裕 on 23/6/2016.
//  Copyright © 2016年 劉裕. All rights reserved.
//

#import "LIUWriteToFileUnit.h"
#import "LIUNote.h"
#import "MarkNoteParser.h"

@implementation LIUWriteToFileUnit

/**
 *  获取笔记标题
 *
 *  @param contentText 文本域文本
 *
 *  @return 处理后的标题
 */
+ (NSString *)getTitle:(NSString *)contentText {
    NSString *title = nil;
    if ([contentText rangeOfString:@"\n"].location != NSNotFound) {
        title = [[contentText componentsSeparatedByString:@"\n"] firstObject];
    } else {
        title = contentText;
    }
    if ([title rangeOfString:@"#"].location != NSNotFound) {
        title = [title substringFromIndex:1];
    }
    return title;
}

+ (BOOL)writeToFile:(LIUNote *)note {
    NSError *error = NULL;
    NSString *idStr = note.idStr;
    
    NSString *createPath = [[NSString.document stringByAppendingPathComponent:@"HTML"] stringByAppendingPathComponent:idStr];
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *file = [idStr stringByAppendingString:@".html"];
    
    NSString *path = [NSString string];
    if ([mgr fileExistsAtPath:createPath]) {
        path = [createPath stringByAppendingPathComponent:file];
    }
    NSString *content = [MarkNoteParser toHtml:note.noteContent];
    NSString *title = note.noteTitle;
    NSString *markdownCss = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"style.css" ofType:nil] encoding:NSUTF8StringEncoding error:nil];
    NSMutableString *html = [@"" mutableCopy];
    [html appendString:@"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>"];
    [html appendString:title];
    [html appendString:@"</title>"];
    [html appendString:@"<style>"];
    [html appendString:markdownCss];
    [html appendString:@"</style></head><body>"];
    [html appendString:content];
    [html appendString:@"</body></html>"];
    
    return [html writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
@end
